<?
require_once("mvc/action/Action.php");
require_once("cms/staff/om/StaffPeer.php");
require_once("cms/staff/om/StaffRolePeer.php");

class SaveAction extends Action {

    private $log;

    public function __construct() {
        $this->log =& LoggerManager::getLogger("SaveAction");
    }

    public function execute(ActionConfig &$mapping, &$form, Request &$request, Response &$response) {

        $errors = new ActionMessages();

        $staff =& $form->getStaff();
        $roles =& $form->getRoles();

        $conn = Propel::getConnection();

        try {

            $conn->begin();

            // Staffname taken check
            $c = new Criteria();
            $c->add(StaffPeer::USERNAME, $staff->getUsername());
            if($staff->getStaffId() > 0)
                $c->add(StaffPeer::STAFF_ID, $staff->getStaffId(), Criteria::NOT_EQUAL);
            $check = StaffPeer::doSelectOne($c, $conn);

            if(!is_null($check)) {
                $errors->add("staff->username",
                    new ActionMessage("Username is already taken."));
                $this->saveErrors($request, $errors);
                return $mapping->getInputForward();
            }

            // process image
            $formImage =& $form->getFormImage();

            if(!$form->getDeleteImage() && $formImage["size"] > 0) {

                $image = $staff->getImageRelatedByImageId();
                $thumb = $staff->getImageRelatedByThumbnailId();

                require_once("cms/core/util/ImageProperties.php");
                $properties = new ImageProperties(
                    $request->getContext()->getInitParameter(_Core::SETTING_LIST)
                );

                require_once("cms/core/util/ImageProcessor.php");
                ImageProcessor::process(
                    $conn, $errors, $formImage,
                    $properties, $image, $thumb
                );

                // Set the generated ids
                $staff->setThumbnailId($thumb->getImageId());
                $staff->setImageId($image->getImageId());

            } else if($form->getDeleteImage()) {

                $image = $staff->getImageRelatedByImageId();
                $thumb = $staff->getImageRelatedByThumbnailId();

                require_once("cms/core/om/BinaryFilePeer.php");

                BinaryFilePeer::doDelete($thumb->getBinaryFile(), $conn);
                BinaryFilePeer::doDelete($image->getBinaryFile(), $conn);
            }

            if($staff->getStaffId() > 0) {

                // Retrieve the old staff
                $oldstaff = StaffPeer::retrieveByPk($staff->getStaffId(), $conn);

                // Delete the old roles
                $c = new Criteria();
                $c->add(StaffRolePeer::USERNAME, $oldstaff->getUsername());
                StaffRolePeer::doDelete($c, $conn);

                // Update staff, using criteria to not touch passwords in db.
                $c = new Criteria();
                $c->add(StaffPeer::STAFF_ID, $staff->getStaffId());
                $c->add(StaffPeer::USERNAME, $staff->getUsername());
                $c->add(StaffPeer::FIRSTNAME, $staff->getFirstname());
                $c->add(StaffPeer::SURNAME, $staff->getSurname());
                $c->add(StaffPeer::REGION, $staff->getRegion());
                $c->add(StaffPeer::SECTOR, $staff->getSector());
                $c->add(StaffPeer::ORGANIZATION, $staff->getOrganization());
                $c->add(StaffPeer::MODIFIED_DATE, date(_Core::FORMAT_SQLDATETIME));
                $c->add(StaffPeer::NEWSLETTER, $staff->getNewsletter());
                $c->add(StaffPeer::THUMBNAIL_ID, $staff->getThumbnailId());
                $c->add(StaffPeer::IMAGE_ID, $staff->getImageId());
                $c->add(StaffPeer::LANGUAGE_CODE, $staff->getLanguageCode());

                if(strlen($staff->getPassword()) > 0 && strlen($form->getPassword2()) > 0)
                    $c->add(StaffPeer::PASSWORD, md5($staff->getPassword()));

                StaffPeer::doUpdate($c, $conn);

            } else {

                $staff->setActive(true);
                $staff->setModifiedDate(date(_Core::FORMAT_SQLDATETIME));
                $staff->setPassword(md5($staff->getPassword()));
                $staff->setInsertDate(date(_Core::FORMAT_SQLDATETIME));
                $staff->setActive(_Core::AUTO_ACTIVATE);
                StaffPeer::doInsert($staff, $conn);

            }

            // Insert the staff roles
            foreach($roles as $role) {
                $staffRole = new StaffRole();
                $staffRole->setUsername($staff->getUsername());
                $staffRole->setRolename($role);
                StaffRolePeer::doInsert($staffRole, $conn);
            }

            $conn->commit();

        } catch(PropelException $e) {
            $conn->rollback();
            $errors->add(ActionMessage::GLOBAL_MESSAGE,
                new ActionMessage("error.save"));
            $this->log->error($e->getMessage());
        }

        // Return any save errors.
        if(!$errors->isEmpty()) {
            $this->saveErrors($request, $errors);
            return $mapping->getInputForward();
        }


        // Reset the staffListForm from & to session.
        $session  = $request->getSession();
        $listForm = $session->getAttribute("cms/staffListForm");
        $listForm->setPage(0);
        $session->setAttribute("cms/staffListForm", $listForm);


        // To the success staff.
        return $mapping->findForward("success");

    }

}
?>